﻿using CommonClass;
using I_Produce.Domains.DTO;
using I_Produce.Domains.Entity;
using I_Produce.Infrastructure.Interface;
using I_Produce.Read.API.Application.Commands.GermlineHistoryRecordsCommand;
using MediatR;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace I_Produce.Read.API.Application.CommandHandlers.GermlineHistoryRecordsHandler
{
    public class GermlineHistoryRecordsQueryCommandHandler : IRequestHandler<GermlineHistoryRecordsQueryCommand, ApiResult<PagerResult<GermlineHistoryRecords>>>
    {

        private readonly IGermlineHistoryRecordsRepository _germlineHistoryRecordsRepository;

        public GermlineHistoryRecordsQueryCommandHandler(IGermlineHistoryRecordsRepository germlineHistoryRecordsRepository)
        {
            _germlineHistoryRecordsRepository = germlineHistoryRecordsRepository;
        }

        public async Task<ApiResult<PagerResult<GermlineHistoryRecords>>> Handle(GermlineHistoryRecordsQueryCommand request, CancellationToken cancellationToken)
        {
            var list = _germlineHistoryRecordsRepository.All().Result.Where(x => !x.IsDel);

            if (!string.IsNullOrEmpty(request.sDateOfBreeding))
            {
                list = list.Where(x => x.DateOfBreeding >= DateTime.Parse(request.sDateOfBreeding));
            }

            if (!string.IsNullOrEmpty(request.eDateOfBreeding))
            {
                list = list.Where(x => x.DateOfBreeding < DateTime.Parse(request.eDateOfBreeding).AddDays(1));
            }

            if (!string.IsNullOrEmpty(request.motherEarHorn))
            {
                list = list.Where(x => x.MotherEarHorn.Contains(request.motherEarHorn));
            }

            var total = list.Count();
            var page = (int)Math.Ceiling(total * 1.0 / request.pageSize);

            list = list.OrderByDescending(x => x.Id).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize);

            return new ApiResult<PagerResult<GermlineHistoryRecords>>
            {
                Code = 200,
                msg = "成功",
                Data = new PagerResult<GermlineHistoryRecords>
                {
                    TotalCount = total,
                    PageCount = page,
                    Datas = list.ToList()
                }
            };
        }
    }
}
